package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ITravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper contentMapper;

    public int deleteByPrimaryKey(Long id) {
        return travelMapper.deleteByPrimaryKey(id);
    }

    /**
     * 作者,创建时间,最后更新时间不是用户创建的
     * 在保存之前需要设置值进去,否则会造成数据丢失
     *
     * @param travel
     * @return
     */
    public int insert(Travel travel) {

        travel.setAuthor(UserContext.getUser());//存到作用域里
        travel.setCreateTime(new Date());
        travel.setLastUpdateTime(new Date());
        //先保存游记表
        travelMapper.insert(travel);

        //再保存游记内容表, 游记内容表中的id=游记表id
        TravelContent travelContent = travel.getTravelContent();
        travelContent.setId(travel.getId());
        return contentMapper.insert(travelContent);
    }

    public Travel selectByPrimaryKey(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    public List<Travel> selectAll() {
        return travelMapper.selectAll();
    }

    /**
     * 更新游记表
     *
     * @param travel
     * @return
     */
    public int updateByPrimaryKey(Travel travel) {

        travel.setLastUpdateTime(new Date());

        //先更新游记表的内容
        travelMapper.updateByPrimaryKey(travel);

        //再更新游记内容表, 游记内容表中的id=游记表id
        TravelContent travelContent = travel.getTravelContent();
        travelContent.setId(travel.getId());
        return contentMapper.updateByPrimaryKey(travelContent);

    }

    public PageInfo queryTravel(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public Travel getById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    public TravelContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    public void changeState(Travel travel) {
        //需要判断是否是发布状态, 是就需要设置发布时间
        if (travel.getState() == Travel.STATE_POST) {
            travel.setReleaseTime(new Date());
        }
        travelMapper.changeStatus(travel);
    }

}
